import { Component, Input, Output, EventEmitter, ChangeDetectorRef } from '@angular/core';
import { ColumnOperation, ColumnHeader } from '../models/columnHeader.model';
import { ColumnOptions } from '../models/columnOptions.model';
import { Subject } from 'rxjs/Subject';
import { AnalyticsService } from '../../../services/googleAnalytics.service';
import { GoogleAnalyticsBeacon } from '../../../models/googleAnalytics.model';


@Component({
    selector: 'column-header',
    templateUrl: './columnHeader.component.html',
    styleUrls: ['./columnHeader.component.scss', '../table.component.scss']
})
export class ColumnHeaderComponent {
    private _options: ColumnOptions;
    @Input() set options(value: ColumnOptions) {
        if (value) {
            this._options = value;
            this.columnStatus.searchIdentifier = value.searchIdentifier;
            this.columnStatus.sortIdentifier = value.sortIdentifier;
        }
    }

    get options(): ColumnOptions{
        return this._options;
    }

    @Output() onChanged: EventEmitter<ColumnHeader> = new EventEmitter();

    public searchValue: string;

    public orderAsc?: boolean;

    public researchAvailable?: boolean = null;

    public dropDownSelectionList: any[];

    private columnStatus: ColumnHeader = new ColumnHeader();
    private valueSubject: Subject<string> = new Subject<string>();

    public dropdownSettings: any = {
        enableSearch: false,
        buttonClasses: 'multi-select-dropdown-button btn btn-default btn-secondary',
        checkedStyle: 'glyphicon',
        dynamicTitleMaxItems: 3,
        showCheckAll: true,
        showUncheckAll: true,
        displayAllSelectedText: true
    };

    constructor(private cdRef: ChangeDetectorRef,
        private analyticsService: AnalyticsService) {
        this.valueSubject
            .debounceTime(400)
            .distinctUntilChanged() // only emit if value is different from previous value
            .subscribe(value => {
                this.orderAsc = true;
                this.columnStatus.operation = ColumnOperation.search;
                this.columnStatus.value = value;
                this.onChanged.emit(this.columnStatus);
            });
    }

    public sort(event: any) {
        if(this._options.canSort)
        {
            this.orderAsc = this.orderAsc == null ? true : !this.orderAsc;
            this.columnStatus.operation = ColumnOperation.sort;
            this.columnStatus.value = this.orderAsc;
            this.onChanged.emit(this.columnStatus);
        }
    }

    public search(value: string) {        
        this.valueSubject.next(value);
    }

    /*public toggleResearch(available?: boolean) {
        this.researchAvailable = available;
        this.search();
    }

    public onDropdownClosed() {
        this.search();
    }*/
}